<?php
/**
 * 用户管理
 * @since   2018-02-06
 */

namespace app\admin\controller\user;

use app\admin\controller\Base;
use app\admin\model\UserMiner;
use app\api\model\User;
use app\util\Tools;
use think\cache\driver\Redis;
use think\facade\Config;
use think\facade\Db;

class Index extends Base {

    /**
     * @OA\Get(
     *   path="/admin/FrontUser/index",
     *   tags={"会员相关"},
     *   summary="会员管理列表",
     *   description="前台用户",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(ref="#/components/parameters/keywords"),
     *   @OA\Parameter(name="type",in="query",example="1",description="搜索类型 1账号 2昵称",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Parameter(ref="#/components/parameters/order"),
     *   @OA\Parameter(ref="#/components/parameters/size"),
     *   @OA\Parameter(ref="#/components/parameters/page"),
     *   @OA\Response(
     *     response="200",
     *     description="返回JSON",
     *     @OA\MediaType(
     *      mediaType="application/json",
     *      @OA\Schema(
     *         @OA\Property(property="code", type="number",description="状态码"),
     *         @OA\Property(property="msg", type="string",description="提示消息"),
     *         @OA\Property(property="data", type="object",description="数据列表",@OA\Items),
     *      )
     *    )
     *   ),
     *   @OA\Response(response="500", description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function index() {

        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $type = $this->request->get('type', '', 'intval');
        $keywords = $this->request->get('keywords', '');
        $status = $this->request->get('status', '');
        $realStatus = $this->request->get('real_status', '');

        $obj = new User();
        if (strlen($status)) {
            $obj = $obj->where('status', $status);
        }
        if (strlen($realStatus)) {
            $obj = $obj->where('real_status', $realStatus);
        }
        $order = 'id DESC';
        if ($type) {
            switch ($type) {
                case 1:
                    $obj = $obj->where('username', '=', $keywords);
                    break;
                case 2:
                    $obj = $obj->where('realname', '=', $keywords);
                    break;
                case 3:
                    $obj = $obj->where('id', '=', $keywords);
                    break;
                case 4:
                    $obj = $obj->where('referrer_id', '=', $keywords);
                    break;
                case 5:
                    $path = User::where('id','=',$keywords)->value('referrer_id_path');
                    $obj = $obj->where('referrer_id_path', 'like', "$path,$keywords%");
                    $order = 'referrer_id ASC';
                    break;
            }
        }

        $listObj = $obj->order($order)
            ->paginate($limit, false, ['page' => $start])->each(function($item, $key){
                $item->userData;
            })->toArray();
        $listInfo = $listObj['data'];

        foreach ($listInfo as $key => &$value) {
            if ($value['userData']) {
                $value['userData']['last_login_time'] = date('Y-m-d H:i:s', $value['userData']['last_login_time']);
                $listInfo[$key]['group_id'] = [];
            }
        }

        $this->success('获取成功'.$obj->getLastSql(),[
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }
    public function real() {

        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $type = $this->request->get('type', '', 'intval');
        $keywords = $this->request->get('keywords', '');

        $obj = new User();
        $obj = $obj->where('real_status', 'in', [2,1]);
        if ($type) {
            switch ($type) {
                case 1:
                    $obj = $obj->whereLike('username', "%{$keywords}%");
                    break;
                case 2:
                    $obj = $obj->whereLike('realname', "%{$keywords}%");
                    break;
            }
        }

        $listObj = $obj->order('real_status DESC')
            ->paginate($limit, false, ['page' => $start])->each(function($item, $key){
                $item->userData;
            })->toArray();
        $listInfo = $listObj['data'];

        foreach ($listInfo as $key => &$value) {
            if ($value['userData']) {
                $value['userData']['last_login_time'] = date('Y-m-d H:i:s', $value['userData']['last_login_time']);
                $listInfo[$key]['group_id'] = [];
            }
        }

        $this->success('获取成功',[
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    /**
     * @OA\Put(path="/admin/FrontUser/checkReal/{id}",
     *   tags={"会员相关"},
     *   summary="审核会员",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   @OA\Parameter(name="memo",in="query",description="备注",@OA\Schema( type="string" )),
     *   @OA\Parameter(name="status",in="query",required=true,description="状态。0驳回，1通过",@OA\Schema( type="integer", format="int32", minimum=1.0 )),
     *   @OA\Response(
     *     response=200,
     *     description="返回Json",
     *     @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *   ),
     *   @OA\Response(response=500, description="服务器错误"),
     *   security={{"App-Login-Token": ""}}
     * )
     */
    public function checkReal($id) {
        $status = $this->request->param('status');
        $memo = $this->request->param('memo');
        if(!$id){
            $this->error('参数错误');
        }
        $find = User::find($id);
        if($find['real_status'] != 2){
            $this->error('不在待审核状态');
        }
        $result = User::update([
            'id' => $id,
            'real_status' => $status,
            'real_memo' => $memo
        ]);
        if (!$result) {
            $this->error('审核失敗');
        }
        if($status == 1){
            $miner = UserMiner::where('uid='.$find->id.' AND type=2')->find();
            if(!empty($miner)){
                unset($miner['miner_info']);
                $miner->status = 1;
                $redis = new Redis();
                $redis->set(config('easyApi.APP_NAME').":miner:experience:$miner[uid]-$miner[id]", $miner->toArray());
            }
            $miner->status = 1;
            $miner->save();
        }
        $content = $status?'恭喜您的实名审核审核通过了':'您的实名审核未通过，附加备注：'.$memo;
        \app\api\model\MessageLog::sendMessage($id, $content);
        $this->success();
    }

    /**
     * @OA\Post(
     *   path="/admin/FrontUser/add",
     *   @OA\Parameter(ref="#/components/parameters/AppClientVersion"),
     *   @OA\Parameter(ref="#/components/parameters/AppDeviceType"),
     *   tags={"会员相关"},
     *   summary="新增会员",
     *   @OA\RequestBody(
     *      @OA\MediaType(
     *         mediaType="application/json",
     *         @OA\Schema(
     *            @OA\Property(property="username", type="string", description="账户"),
     *            @OA\Property(property="nickname", type="string", description="昵称"),
     *            @OA\Property(property="password", type="string", description="密码"),
     *            @OA\Property(property="referrer_id", type="string", description="推荐人用户ID"),
     *            example={"username":"18888888800","nickname":"用户一","password":"123456","referrer_id":0}
     *         )
     *       )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="OK",
     *         @OA\JsonContent( type="array", @OA\Items(ref="#/components/schemas/response" ) )
     *     ),
     *     @OA\Response(response="500", description="服务器错误"),
     *     security={{"App-Login-Token": ""}}
     * )
     */
    public function add() {
        $postData = $this->request->post();
        $postData['create_ip'] = request()->ip();
        $postData['password'] = Tools::userMd5($postData['password']);
        $find = User::where(['username'=>$postData['username']])->find();
        if(!empty($find)){
            $this->error('已存在账户');
        }
        if($postData['referrer_id']){
            $referrerId = $postData['referrer_id'];
            $referrer = User::where(['id' => $referrerId])->find();
            if(empty($referrer)){
                $this->error('推荐人不存在!');
            }
            $referrer = $referrer->toArray();
            $postData['referrer_id'] = $referrerId;
            $postData['referrer_id_path'] = $referrer['referrer_id_path'].','.$referrerId;
            $postData['referrer_level'] = $referrer['referrer_level']+1;
        }
        $res = User::create($postData);
        if ($res === false) {
            $this->error();
        } else {
            \app\api\model\BlockchainAccount::initAccount($res->id);
            $this->success();
        }
    }

    /**
     * 用户状态编辑
     * @return array
     */
    public function changeStatus($id) {
        $status = $this->request->param('status');
        $res = User::update([
            'id'     => $id,
            'status' => $status
        ]);
        if ($res === false) {
            $this->error();
        } else {
            User::deleteRedisUserInfo($id);
            $this->success();
        }
    }

    /**
     * 编辑用户
     * @return array
     * @throws \think\exception\DbException
     */
    public function edit($id) {
        $postData = $this->request->param();
        if ($postData['password'] === 'password') {
            unset($postData['password']);
        } else {
            $postData['password'] = Tools::userMd5($postData['password']);
        }
        $user = User::find($id);
        if(!$user){
            $this->error('不存在该用户');
        }
        $res = $user->allowField(['nickname', 'password', 'phone', 'status', 'type'])->save($postData);
        if ($res === false) {
            $this->error();
        } else {
            User::deleteRedisUserInfo($id);
            $this->success();
        }
    }

    /**
     * 删除用户
     * @return array
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error( '缺少必要参数');
        }
        User::destroy($id);
        User::deleteRedisUserInfo($id);
        $this->success();
    }

}
